/**
 * 一次性将数据加载到端端处理
 */
!(function ($, window, document, undefined) {
    'use strict';

    var language = {
        sProcessing: '<img src="/images/loader10.gif">',
        sLengthMenu: '_MENU_ 条记录每页',
        sZeroRecords: '没有匹配结果',
        sInfo: '第 _PAGE_ 页 ( 总共 _PAGES_ 页 / _TOTAL_ 条 )',
        sInfoEmpty: '无记录',
        sInfoFiltered: '(由 _MAX_ 项结果过滤)',
        sInfoPostFix: '',
        sSearch: '搜索：',
        sUrl: '',
        sEmptyTable: '表中数据为空',
        sLoadingRecords: '载入中...',
        sInfoThousands: ',',
        oPaginate: {
            sFirst: '首页',
            sPrevious: '上一页',
            sNext: '下一页',
            sLast: '尾页'
        },
        oAria: {
            sSortAscending: ': 以升序排列此列',
            sSortDescending: ': 以降序排列此列'
        }
    };

    // grid defaults
    var defaults = {
        pagingType: 'full',
        language: language,
        autoWidth: true,
        lengthChange: true,
        ordering: true,
        paging: true,
        processing: false,
        scrollX: true,
        searching: true,
        serverSide: false,
        stateSave: false,
        destory: true,
        displayStart: 0,
        dom: '',
        select: {
            style: 'multi',
            selector: 'td:first-child'
        },
        pageLength: 10,
        order: [],
        columns: [],
        data: []
    };

    // var $opts = {
    //     gridName: 'table', // 表格名称，必填
    //     removeUrl: 'xxx/remove', // 删除路径，可选
    //     // 删除操作，可选
    //     remove: {
    //         url: '', // 删除路径，必填
    //         // 回调方法，必填
    //         beforeRemove: function (row) {
    //             return true;
    //         }
    //     },
    //     tools: '', // 操作按键组，可选
    //     checkbox: true, // 全选 checkbox，默认安装，可选
    //     sequence: true, // 显示表格序列，可选
    //     searchTip: '', // 快捷搜索tip
    //     // 表格属性，必填
    //     gridOptions: {
    //         // 列，必填
    //         columns: [{}]
    //     },
    //     ajax: {
    //         url: '', // 请求数据url，必填
    //     },
    //     initCallback: function () {
    //         // 初始化完成回调方法，可选
    //     },
    //     drawCallback: function () {
    //         // 重画完成回凋方法，可选
    //     }
    // };

    var DGrid = function (element, options) {
        this.$this = element;
        this.$opts = options;
    };


    /**
     * 加载cols与data使用
     * @param options
     */
    var ajaxGrid = function (options) {
        var defaults = {
            type: 'POST',
            url: '',
            data: {},
            dataType: 'JSON',
            async: false,
            success: function (data) {
            },
            error: function (msg) {
                console.error(msg);
            }
        };
        var _options = $.extend(true, {}, defaults, options);
        $.ajax(_options);
    };

    /**
     * ajax
     */
    var ajax = function (params, fn) {
        $.ajax({
            type: 'POST',
            url: params.url,
            data: params.data,
            dataType: 'JSON',
            async: false,
            success: function (data) {
                layer.msg(data.message, {
                    offset: '120px'
                });
                if (fn) {
                    fn();
                }
            },
            error: function (msg) {
                layer.msg(msg.responseText, {
                    offset: '120px'
                });
            }
        });
    };


    /**
     * 单元格编辑
     * @param $this
     * @param id
     * @param url
     */
    var xedit = function ($this, opt) {
        $this.editable({
            // mode : 'inline',
            defaultValue: '',
            pk: 1,
            showbuttons: false,
            emptytext: '--',
            placement: 'right',
            success: function (response, newValue) {
                var data = {
                    id: opt.id
                };
                data[opt.v] = newValue;
                var params = {
                    data: data,
                    url: opt.url
                };
                ajax(params);
            }
        });
    };

    /**
     * 初始化搜索框
     *
     * @param datas
     */
    var initSearch = function ($opts, datas) {
        var search = $opts.search;
        if (!search) {
            $('form.search-frm').remove();
            return;
        }
        var ldatas = [];
        $.each(datas, function (i, data) {
            var searchable = data.searchable;
            if (searchable) {
                ldatas.push(data);
            }
        });
        var fgroups = [];
        var fgroup = '<div class="form-group">{0}</div>';
        var linput = '\
				<label class="col-sm-1 control-label">{0}：</label>\
	            <div class="col-sm-3">\
	              <input type="text" name="{1}" class="form-control input-sm" />\
	            </div>\
			';
        var len = ldatas.length, size = 3, index = 0;
        var page = parseInt((len + size - 1) / size);
        for (var i = 0; i < page; i++) {
            var linputs = [];
            for (var j = 0; j < size; j++) {
                var data = ldatas[index];
                if (data) {
                    linputs.push(linput.format(data.title, data.columnName));
                    index++;
                } else {
                    break;
                }
            }
            fgroups.push(fgroup.format(linputs.join('')));
        }
        var html = fgroups.join('');
        $(document).find('.search-div').html(html);
    };

    DGrid.prototype = {
        constructor: DGrid,
        loadColumns: function (options) {
            var $opts = this.$opts;
            // load data
            var load_data_options = $.extend(true, {}, $opts.ajax, {
                success: function (data) {
                    $.extend(true, options.data, data);
                }
            });
            ajaxGrid(load_data_options);
        },
        render: function (options) {
            if (options.columns) {
                $.each(options.columns, function (i, c) {
                    if (c.render) {
                        c.render = eval('(' + c.render + ')');
                    }
                });
            }
        },
        toolDiv: function () {
            var div = $('#' + this.$this.attr('id') + '_wrapper');
            return div;
        },
        checkbox: function (options) {
            var e = this;
            var classValue = options.showDetail ? 'select-checkbox details-control' : 'select-checkbox';
            options.columns.unshift({
                orderable: false,
                searchable: false,
                data: null,
                className: classValue,
                defaultContent: '',
                title: '<input class="' + e.$opts.gridName + '-table-select" type="checkbox" />',
                width: 10
            });
        },
        // 安装 sequence 显示行
        sequence: function (options) {
            options.columns.unshift({
                orderable: false,
                searchable: false,
                data: null,
                defaultContent: '',
                className: 'sequence',
                width: 10
            });
        },
        // 默认按第一个支持排序的列排序，都不支持，则取最后一列
        order: function (options) {
            var $opts = this.$opts;
            var selfOrder = $opts.gridOptions.order;
            if (selfOrder) {
                return; // 存在自定义排序，则不再执行系统默认排序
            }
            var cols = options.columns;
            var len = cols.length;
            var order = [];
            $.each(cols, function (i, c) {
                var isOrder = c.orderable == false ? false : true;
                if (isOrder || (i == (len - 1))) {
                    order.push([i, 'desc']);
                    return false;
                }
            });
            $.extend(true, options.order, order);
        },
        initEditableCols: function (options) {
            if (options.columns) {
                var edits = [];
                $.each(options.columns, function (i, c) {
                    if (c.editable) {
                        var key = 'td:eq({0})'.format(i);
                        var edit = {};
                        edit[key] = c.data;
                        edits.push(edit);
                    }
                });
                this.$edits = edits;
            }
        },
        xEdit: function (nRow, aData) {
            var edits = this.$edits;
            var $opts = this.$opts;
            var text = '<span>{0}</span>';
            $(edits).each(function (i, edit) {
                $.each(edit, function (k, v) {
                    var val = $(k, nRow).text();
                    $(k, nRow).html(text.format(val));
                    xedit($(k, nRow).find('span'), {id: aData.id, url: $opts.editUrl, v: v});
                });
            });
        },
        myGrid: function () {
            var e = this, $opts = e.$opts, $this = e.$this;
            var toolId = $opts.toolId ? $opts.toolId : ('#' + $opts.gridName + '_tool');
            var _options = {
                columns: [],
                dom: ('<"row"<"' + toolId + '.col-xs-6"><"col-xs-6"f>r>t<"row"<"col-xs-3"l><"col-xs-3"i><"col-xs-6"p>>'),
                initComplete: function () {
                    // 添加操作按钮
                    e.toolDiv().find(toolId).append($opts.tools);
                    // 删除方法
                    if ($opts.removeUrl || $opts.remove) {
                        e.toolDiv().find('div.btn-group').find('a.oper-delete').click(function () {
                            e.remove();
                        });
                    }
                    // 初始化完成后回调
                    if ($opts.initCallback) {
                        $opts.initCallback();
                    }
                },
                drawCallback: function (settings) {
                    var table = e.getTable();
                    // 页面初始化完成后回调
                    if ($opts.drawCallback) {
                        $opts.drawCallback(table);
                    }
                },
                fnRowCallback: function (nRow, aData, iDisplayIndex) {
                    /*
                     * row特殊处理
                     */
                    e.xEdit(nRow, aData);
                    return nRow;
                }
            };
            // console.log(defOpts);
            // combine defaults conf
            var options = $.extend(true, {}, defaults, _options, $opts.gridOptions);
            // combine the settings
            e.loadColumns(options);
            // convert render to object
            e.render(options);
            // 安装 全选&取消全选 控件，默认安装
            var checkbox = $opts.checkbox == false ? false : true;
            if (checkbox) {
                e.checkbox(options);
            }
            // 安装序列显示行
            if ($opts.sequence) {
                e.sequence(options);
                options.select = true;
            }
            // 处理排序
            e.order(options);
            // 初始化可编辑单元格
            e.initEditableCols(options);
            /**
             * 使用自定义错误
             * @param settings
             * @param tn
             * @param msg
             */
            $.fn.dataTable.ext.errMode = function (settings, tn, msg) {
                if (tn == 1 || tn == 7) {
                    var errorMsg = '服务器开小差去了，请稍后重试！';
                    layer.msg(errorMsg, {icon: 5, offset: '100px'});
                    console.log(tn, msg);
                }
            };
            console.log(options);
            // var table = $this.DataTable(options);
            var table = $this.dataTable(options).api();

            if ($opts.searchTip) {
                e.toolDiv().find('input[type="search"]').attr('placeholder', $opts.searchTip);
            }

            // set table for get
            e.$table = table;
            // select
            e.select();
            // change page length
            e.changePageLength();
            // order
            e.orderSearch();
            // 数据一次性加载到页面，服务端搜索失效
            // e.search();
            return $this;
        },
        getTable: function () {
            return this.$table;
        },
        select: function () {
            var table = this.getTable();
            this.toolDiv().find('input.' + this.$opts.gridName + '-table-select').click(function () {
                var checked = $(this).prop('checked');
                if (checked) {
                    // 全选
                    table.rows().select();
                } else {
                    // 取消全选
                    table.rows().deselect();
                }
            });
        },
        changePageLength: function () {
            var e = this;
            var table = e.getTable();
            table.on('length.dt', function () {
                table.rows().deselect();
            });
        },
        orderSearch: function () {
            var e = this;
            var table = e.getTable();
            table.on('search.dt order.dt', function () {
                var ck = e.toolDiv().find('input.table-select');
                ck.attr('checked') == 'checked' ? ck.removeAttr('checked') : '';
                table.rows().deselect();
            });
        },
        addRows: function (items) {
            var e = this;
            var table = e.getTable();
            table.rows().add(items).draw(false);
        },
        reomveRows: function () {
            var e = this;
            var table = e.getTable();
            table.rows('.selected').remove().draw(false);
        },
        selectItems: function () {
            var e = this;
            var table = e.getTable();
            var items = table.rows({
                selected: true
            }).data();
            if (items.length == 0) {
                layer.msg('至少选择一条！', {
                    offset: '120px'
                });
                return;
            }
            return items;
        },
        selectIds: function () {
            var e = this;
            var items = e.selectItems();
            if (!items) {
                return;
            }
            var ids = $.map(items, function (item, i) {
                return item.id;
            });
            return ids;
        },
        // 获取选择记录的属性值集合
        selectFields: function (key) {
            var items = this.selectItems();
            if (!items) {
                return;
            }
            var items = $.map(items, function (item, i) {
                return item[key];
            });
            return items;
        },
        // 获取选择记录的第一行 id
        selectId: function () {
            return this.selectIds()[0];
        },
        // 获取选择的第一行记录
        selectItem: function () {
            return this.selectItems()[0];
        },
        // 获取选择的第一行记录的属性值
        selectField: function (key) {
            return this.selectFields(key)[0];
        },
        // 跳转到指定页面
        gotoPageNum: function (pageNum) {
            this.getTable().fnPageChange(Number(pageNum) - 1);
        },
        // 添加序列
        addSequence: function () {
            var t = this.getTable();
            t.on('order.dt search.dt', function () {
                t.column(0, {search: 'applied', order: 'applied'}).nodes().each(function (cell, i) {
                    cell.innerHTML = i + 1;
                });
            }).draw();
        },
        // 删除方法
        remove: function () {
            var e = this;
            var $opts = e.$opts;
            var ids = e.selectIds();
            if (!ids) {
                return;
            }
            var remove = $opts.remove;
            if (remove) {
                var row = e.selectItem();
                var doRemove = remove.beforeRemove(row);
                if (!doRemove) {
                    return;
                }
            }
            var url = $opts.remove ? $opts.remove.url : $opts.removeUrl;
            var params = {
                data: {
                    ids: ids.join(',')
                },
                url: url
            };
            layer.confirm('再看一眼，确认要删除么？', {
                offset: '100px'
            }, function () {
                ajax(params, function () {
                    e.reload();
                });
            });
        },
        reload: function () {
            var table = this.getTable();
            var $opts = this.$opts;
            var load_data_options = $.extend(true, {}, $opts.ajax, {
                success: function (data) {
                    table.clear().draw();
                    table.rows.add(data).draw();
                }
            });
            ajaxGrid(load_data_options);
        },
        search: function () {
            var table = this.getTable();
            $(window.document).find('.btn-primary').click(function () {
                table.draw();
            });
        }
    };

    $.fn.DGrid = function (options) {
        var grid = new DGrid(this, options);
        grid.myGrid();
        if (options.sequence) {
            grid.addSequence();
        }
        return grid;
    };

    $.fn.DGrid.Constructor = DGrid;

})(jQuery, window, document);